<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇游戏</title>
    <style>
        body { margin: 0; }
        canvas { background: #eee; display: block; margin: 0 auto; }
    </style>
</head>
<body>
    <canvas id="gameCanvas" width="400" height="400"></canvas>
    <script>
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');

        const boxSize = 20;
        const gridWidth = canvas.width / boxSize;
        const gridHeight = canvas.height / boxSize;

        let snake = [{ x: 5, y: 5 }];
        let food = { x: Math.floor(Math.random() * gridWidth), y: Math.floor(Math.random() * gridHeight) };
        let dx = 1; // Direction x
        let dy = 0; // Direction y
        let gameLoop; // 用于存储setTimeout返回的ID，以便之后可以清除它

        document.addEventListener('keydown', changeDirection);

        function changeDirection(event) {
            if (event.key === 'ArrowUp' && dy === 0) { dy = -1; dx = 0; }
            if (event.key === 'ArrowDown' && dy === 0) { dy = 1; dx = 0; }
            if (event.key === 'ArrowLeft' && dx === 0) { dx = -1; dy = 0; }
            if (event.key === 'ArrowRight' && dx === 0) { dx = 1; dy = 0; }
        }

        function drawBox(x, y, color) {
            ctx.fillStyle = color;
            ctx.fillRect(x * boxSize, y * boxSize, boxSize, boxSize);
        }

        function moveSnake() {
            const head = { ...snake[0] };
            head.x += dx;
            head.y += dy;

            // Check for game over
            if (
                head.x < 0 ||
                head.x >= gridWidth ||
                head.y < 0 ||
                head.y >= gridHeight ||
                snake.slice(1).some(segment => segment.x === head.x && segment.y === head.y)
            ) {
                clearInterval(gameLoop); // 清除游戏循环
                alert('游戏结束！');
                location.reload();
                return;
            }

            snake.unshift(head);

            // Check for eating food
            if (head.x === food.x && head.y === food.y) {
                food = { x: Math.floor(Math.random() * gridWidth), y: Math.floor(Math.random() * gridHeight) };
            } else {
                snake.pop();
            }

            draw(); // 绘制新的游戏状态
        }

        function draw() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            snake.forEach((segment, index) => {
                drawBox(segment.x, segment.y, index === 0 ? 'green' : 'gray');
            });

            drawBox(food.x, food.y, 'red');
        }

        function startGame() {
            draw(); // 初始绘制
            gameLoop = setInterval(moveSnake, 500); // 每500毫秒移动一次
        }

        startGame(); // 开始游戏
    </script>
</body>
</html>